﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using Microsoft.AspNet.SignalR;
using DrillOnline.Services;
using System.Threading.Tasks;
using DrillOnline.Services.Scenarios;

namespace DrillOnline.Hubs
{
    //public class UserEventStatus
    //{
    //    /// <summary>
    //    /// 断开连接的用户不会立即移除，而是标记为disconnected.
    //    /// 用于保留他的记录但不给他发信息。
    //    /// </summary>
    //    public bool IsDisconnected { get; set; }
    //    public int SecOffset { get; set; }
    //    public string UserName { get; set; }
    //    public string Group { get; set; }

    //}
    public class DrillEventHub : Hub
    {
        DrillHubUtility utility = null;
        public DrillEventHub()
        {
            utility = new DrillHubUtility();
        }
        //public SortedList<string, UserEventStatus> Users = new SortedList<string, UserEventStatus>();
        
        public override System.Threading.Tasks.Task OnConnected()
        {
            var ds = ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
            if (null == ds) return null;

            return Task.Factory.StartNew(async () =>
            {
                await base.OnConnected();
                var u = Context.User.Identity.Name;
                var g = u == "管理员" ? "[管理组]" : ds.ActorGroups.First(v => v.Examiners.Any(j=>j.ActorKey==u)|| v.Actors.Any(j => j.ActorKey == u)).GroupKey;

                await Groups.Add(Context.ConnectionId, g);

                //utility.BroadcastMessage(ds,"管理员","管", "[管理组]", null,"欢迎加入", u + " 加入组 " + g);
            });
        }
        //public override System.Threading.Tasks.Task OnDisconnected()
        //{
        //    return Task.Factory.StartNew(async () =>
        //    {
        //        await base.OnDisconnected();

        //        //todo:a delay action use task,remove his userinstance from user-secoffset history list when timeout.
        //        string u = Context.User.Identity.Name;
        //        if (Users.ContainsKey(u))
        //        {
        //            Users[u].IsDisconnected = true;
        //            if (!OnDisconnectClearTasks.ContainsKey(u))
        //            {
        //                var cs = new CancellationTokenSource();
        //                OnDisconnectClearTasks.Add(u, cs);
        //                var dt = Task.Delay(1000 * 60 * 5, cs.Token);
        //                dt.Wait();
        //                OnDisconnectClearTasks.Remove(u);

        //                if (dt.IsCompleted)
        //                {
        //                    Users.Remove(u);
        //                }

        //            }
        //        }
        //    });
        //}
        //SortedList<string, CancellationTokenSource> OnDisconnectClearTasks = new SortedList<string, CancellationTokenSource>();
        //public override System.Threading.Tasks.Task OnReconnected()
        //{
        //    string u = Context.User.Identity.Name;
        //    if (OnDisconnectClearTasks.ContainsKey(u))
        //    {
        //        OnDisconnectClearTasks[u].Cancel();
        //    }
        //    //todo:if has a ondisconnect clear task, 
        //    //send read more old message link.
        //    //fetch all from his last offset
        //    return base.OnReconnected();


        //}

        public void SendMessage(string msgtype, string targetGroups, string message,string targetEventID)
        {
            var ds = ScenariosHost.Instance.Sessions["default"] as DrillScenarios;

            if (null == ds) return;
            var u = Context.User.Identity.Name;
            var g = u == "管理员" ? "[管理组]" : ds.ActorGroups.First(v => v.Actors.Any(j => j.ActorKey == u)).GroupKey;
            var f = u == "管理员" ? "管" : ds.ActorGroups.First(v => v.Actors.Any(j => j.ActorKey == u)).Model.Flag;

            //if ("submit".Equals(msgtype, StringComparison.CurrentCultureIgnoreCase)) { 
                
            //}
            
            ds.BroadcastMessage(u,f, g, string.IsNullOrEmpty(targetGroups)?null:targetGroups.Split(','), message,msgtype,targetEventID,Context);
        }
        public void QueryOldEvents() {
            var ds = ScenariosHost.Instance.Sessions["default"] as DrillScenarios;
            var u = Context.User.Identity.Name;
            var g = u == "管理员" ? "[管理组]" : ds.ActorGroups.First(v => v.Actors.Any(j => j.ActorKey == u)).GroupKey;

            utility.QueryOldEvents(ds,u,g);

        }
    }


}